package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityGifConvertBinding;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;

public class GifConvertActivity extends BaseAc<ActivityGifConvertBinding> {

    public static String videoPath;
    private int mFps = 10;
    private float mSpeed = 1.0f;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_gif_convert;
    }

    @Override
    protected void initView() {
        mDataBinding.ivGifConvertBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.tvGifConvertDerive.setOnClickListener(this);
        mDataBinding.tvFps1.setOnClickListener(this);
        mDataBinding.tvFps2.setOnClickListener(this);
        mDataBinding.tvFps3.setOnClickListener(this);
        final String[] playSpeeds = getResources().getStringArray(R.array.ve_play_speed);
        int speedPos = (int) ((1f * mDataBinding.sbSpeed.getProgress()) / mDataBinding.sbSpeed.getMax() * (mDataBinding.sbSpeed.getTickCount() - 1));
        mSpeed= Float.parseFloat(playSpeeds[speedPos]);
        mDataBinding.sbSpeed.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                String selSpeed = playSpeeds[seekParams.thumbPosition];
                mSpeed= Float.parseFloat(selSpeed);
            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvFps1:
                clearSelection();
                mDataBinding.tvFps1.setBackgroundResource(R.drawable.shape_speed1);
                mFps = 5;
                break;
            case R.id.tvFps2:
                clearSelection();
                mDataBinding.tvFps2.setBackgroundResource(R.drawable.shape_speed1);
                mFps = 10;
                break;
            case R.id.tvFps3:
                clearSelection();
                mDataBinding.tvFps3.setBackgroundResource(R.drawable.shape_speed1);
                mFps = 15;
                break;
            case R.id.tvGifConvertDerive:
                startConvert();
                break;
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
    }

    private void startConvert(){
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);

        int width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
        int height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
        if (width * height > 960 * 540) {
            //原视频分辨率过大，则要缩小一倍
            width = width / 2;
            height = height / 2;
        }
        Log.e("TAG", "startConvert: "+mSpeed );
        EditorHolder.editor().video2Gif(videoPath, width, height, mFps, mSpeed, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                //保存到相册
                FileP2pUtil.copyPrivateImgToPublic(mContext, outFilePath);
                ToastUtils.showShort(getString(R.string.save_to_album));
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.conv_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.save_video_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置播放器
        setPlayer();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    private void clearSelection() {
        mDataBinding.tvFps1.setBackgroundResource(R.drawable.shape_speed2);
        mDataBinding.tvFps2.setBackgroundResource(R.drawable.shape_speed2);
        mDataBinding.tvFps3.setBackgroundResource(R.drawable.shape_speed2);
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

}